package in.muton.edushare.poll.questions;

import in.muton.edushare.pages.EduShareBasePage;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.PropertyModel;

import com.edushare.common.constants.ApplicationConstants;
import com.edushare.common.dao.UserPollDAO;
import com.edushare.common.util.StringUtil;
import com.edushare.common.vo.PollQuestions;

public class ShortTextQuestion extends QuestionBase {
	private static final long serialVersionUID = -1512304278629653627L;
	private String answer = "";
	private static final Log log = LogFactory.getLog(ShortTextQuestion.class);

	public String getAnswer() {
		log.debug("Reading the model value "+answer);
		return answer;
	}

	public void setAnswer(String ans) {
		log.debug("Setting the model value "+ans);
		this.answer = ans;
	}

	public ShortTextQuestion(String id, IModel<PollQuestions> model,
			EduShareBasePage page, final boolean preview, final boolean editMode) {
		super(id, model, page, preview, editMode);
		retrieveValues();
		add(new TextField<String>("answer", new PropertyModel<String>(this,
				"answer")));
	}

	@Override
	public boolean retrieveValues() {
		setAnswer(new UserPollDAO(getORMInterface()).getStringAnswer(
				getLoggedInUser(), getQuestionModel().getObject()));
		if (StringUtil.isValid(getAnswer()))
			return true;
		return false;
	}

	@Override
	public boolean save(boolean draft) {
		log.debug("Save :" + getAnswer());
		if (isPreview() || isEditMode() || (!draft && !verify()))
			return false;
		UserPollDAO uPDao = new UserPollDAO(getORMInterface());
		uPDao.setAnswer(getLoggedInUser(), getQuestionModel().getObject(),
				getAnswer());
		log.debug("After Save :" + getAnswer());
		return true;
	}

	@Override
	public boolean verify() {
		log.debug("Verifying :" + getAnswer());
		if (!StringUtil.isValid(getAnswer())
				&& getQuestionModel().getObject().isRequired()) {
			setError("Please respond to question no. "
					+ getQuestionModel().getObject().getQuestionSerialNo());
			return false;
		}
		if(StringUtil.isValid(getAnswer()) && 
				getAnswer().length() >= ApplicationConstants.SHORT_QUESTION_LENGTH){
			setError("Your response to question no. "+ getQuestionModel().getObject().getQuestionSerialNo()+" is too long. Limit is 255 characters.");
			return false;
		}
		return true;
	}

	@Override
	public void clear() {
		log.debug("Clearing the text :" + getAnswer());
		new UserPollDAO(getORMInterface()).clearAnswers(getLoggedInUser(),
				getQuestionModel().getObject());
		setAnswer("");
		log.debug("After clearing :" + getAnswer());
	}
}
